package com.wjf.birdfish.easyui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeNode {
	public static final String STATE_OPEN = "opened";
	private static final String STATE_CLOSE = "closed";
	
	private String id;
	private String text;
	private boolean checked;
	private String target;
	private String state = STATE_OPEN;
	
	private Map<String, String> attributes = new HashMap<String, String>();
	
	private List<TreeNode> children = new ArrayList<TreeNode>();

	public String getId() {
		return id;
	}
	
	public void setAttribute(String key, String value) {
		if (key == null) {
			return;
		}
		this.attributes.put(key, value);
	}
	
	public String getAttribute(String key) {
		if (key == null) {
			return null;
		}
		return this.attributes.get(key);
	}
	
	public void removeAttribute(String key) {
		if (key == null) {
			return;
		}
		this.attributes.remove(key);
	}
	
	public Map<String, String> getAttributes() {
		return this.attributes;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public boolean isChecked() {
		return checked;
	}

	public void setChecked(boolean checked) {
		this.checked = checked;
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}
	
	public void addChild(TreeNode child) {
		if (child == null) {
			return;
		}
		this.children.add(child);
	}
	
	public void removeChild(TreeNode child) {
		if (child == null) {
			return;
		}
		this.children.remove(child);
	}
	
	public List<TreeNode> getChildren() {
		return this.children;
	}

	@Override
	public String toString() {
		StringBuilder json = new StringBuilder();
		json.append("{");
		if (this.id == null) {
			this.id = Long.toString(System.nanoTime());
		}
		json.append("id:'").append(this.id).append("'");
		json.append(", text:'").append(this.text).append("'");
		json.append(", checked:'").append(this.checked).append("'");
		json.append(", state:'").append(this.state).append("'");
		if (this.target != null) {
			json.append(", target:'").append(this.target).append("'");
		}
		if (!this.children.isEmpty()) {
			json.append(",children:").append(this.children);
		}
		json.append("}");
		return json.toString();
	}
	
	public boolean isOpen() {
		return STATE_OPEN.equals(this.state);
	}
	
	public boolean isClose() {
		return !isOpen();
	}
	
	public void setOpen() {
		this.state = STATE_OPEN;
	}
	
	public String getState() {
		return this.state;
	}
	
	public void setClose() {
		this.state = STATE_CLOSE;
	}
	
}
